<?php

namespace App\Console\Commands\Opus;

use App\Datas\Opus;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;
use Ixudra\Curl\Facades\Curl;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Green\Green;
use App\Datas\User;


class ReviewOpusImg extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'review:opusimg';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '阿里云审核作品图片';

    protected $accesskeyid;
    protected $accesskeysecret;

    protected $userModel;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->accesskeyid = config("ooss.accesskeyid");
        $this->accesskeysecret = config("oss.accesskeysecret");
        $this->userModel = new User();
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        while (true) {
            $data = DB::table('opus')->select(["id","url","type"])->where(['review_status' => 0])->orderBy("id")->offset(0)->limit(50)->get();

            if (count($data) > 0) {

                try {
                    // 请替换成您的AccessKey ID、AccessKey Secret。
                    AlibabaCloud::accessKeyClient($this->accesskeyid, $this->accesskeysecret)
                        ->timeout(10) // 超时10秒，使用该客户端且没有单独设置的请求都使用此设置。
                        ->connectTimeout(3) // 连接超时3秒，当小于1秒时，则自动转换为毫秒，使用该客户端且没有单独设置的请求都使用此设置。
                        ->regionId('cn-beijing')
                        ->asDefaultClient();

                    $taskArr = [];
                    foreach ($data as $opus) {
                        $taskArr[] = ['dataId' => $opus->id, 'url' => $opus->url];
                        $bizType = $opus->type == 1 ? 'aipaintersd' : 'aipainter';

                        /* 设置待检测的图片，一张图片对应一个检测任务。
                         * 多张图片同时检测时，处理时间由最后一张处理完的图片决定。
                         * 通常情况下批量检测的平均响应时间比单张检测要长。一次批量提交的图片数越多，响应时间被拉长的概率越高。
                         * 代码中以单张图片检测作为示例，如果需要批量检测多张图片，请自行构建多个检测任务。
                         * OCR检测按照实际检测的图片张数*检测的卡证类型单价计费。
                         * ********* 要增加scenes 检测场景，下面foreach ($sceneResults as $sceneResult) 这里需要根据业务更改逻辑
                         */
                        $response = Green::v20180509()->imageSyncScan()
                            ->timeout(10) // 超时10秒，request超时设置，仅对当前请求有效。
                            ->connectTimeout(3) // 连接超时3秒，当小于1秒时，则自动转换为毫秒，request超时设置，仅对当前请求有效。
                            ->body(json_encode(array('tasks' => $taskArr, 'scenes' => array('porn'), 'bizType' => $bizType)))
                            ->request();
                        if (200 == $response->code) {
                            $taskResults = $response->data;
                            foreach ($taskResults as $taskResult) {
                                $blockData = DB::table('opus')->select(["user_id", "use_dot", "task_id"])->where('id', '=', $taskResult->dataId)->first();
                                $key = 'painter:task:' . $blockData->task_id;
                                if (200 == $taskResult->code) {
                                    $sceneResults = $taskResult->results;
                                    foreach ($sceneResults as $sceneResult) {
                                        $suggestion = $sceneResult->suggestion;
                                        if ($suggestion != 'pass') {
                                            $reviewStatus = 2;
                                            $taskStatus = 2;

                                            //该作品用点数购买返还次数+点数
                                            if ($blockData && $blockData->use_dot > 0) {
                                                $this->userModel->updateDot($blockData->user_id, $blockData->use_dot, 6);
                                                $this->userModel->setRemainCount($blockData->user_id, -1);
                                                Redis::hset($key, "url", "https://overseas-files.dalleai.art/default-dot.png");
                                            } else {
                                                Redis::hset($key, "url", "https://overseas-files.dalleai.art/default.png");
                                            }
                                        } else {
                                            $taskStatus = 2;
                                            $reviewStatus = 1;
                                        }

                                        DB::table('opus')->where(['id' => $taskResult->dataId])->update(['review_status' => $reviewStatus]);
                                        Redis::hset($key, "status", $taskStatus);
                                    }
                                } else {
                                    Redis::hset($key, "status", 2);
                                    DB::table('opus')->where(['id' => $taskResult->dataId])->update(['review_status' => 2]);
                                    //该作品用点数购买返还次数+点数
                                    if ($blockData && $blockData->use_dot > 0) {
                                        $this->userModel->updateDot($blockData->user_id, $blockData->use_dot, 6);
                                        $this->userModel->setRemainCount($blockData->user_id, -1);
                                        Redis::hset($key, "url", "https://aipainter-images.dalleai.art/default-dot.png");
                                    } else {
                                        Redis::hset($key, "url", "https://aipainter-images.dalleai.art/default.png");
                                    }
                                }
                            }
                        } else {
                            //Log::info('revirewOpusImgError：', "detect not success. code:" . $response->code . "-----data:".json_encode($taskArr) . "-----requestId:" . $response->requestId);
                        }
                    }
                    
                } catch (Exception $exception) {
                    //Log::info('revirewOpusImgError：', $exception->getMessage());
                }
                
            }
            sleep(1);
        }    
    }
}
